package com.example.sprintboot.service.impl;

import com.example.sprintboot.entity.Order;
import com.example.sprintboot.entity.OrderItem;
import com.example.sprintboot.entity.Payment;
import com.example.sprintboot.mapper.OrderItemMapper;
import com.example.sprintboot.mapper.OrderMapper;
import com.example.sprintboot.mapper.PaymentMapper;
import com.example.sprintboot.service.OrderService;
import com.example.sprintboot.vo.OrderDetailVO;
import com.example.sprintboot.entity.UserAddress;
import com.example.sprintboot.mapper.UserAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sprintboot.mapper.ProductMapper;
import com.example.sprintboot.entity.Product;
import com.example.sprintboot.service.ProductService;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Integer userId, Integer addressId, List<OrderItem> items, String remark) {
        // 1. 查库补全每个商品价格，并校验库存
        for (OrderItem item : items) {
            Product product = productService.getProductById(item.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在，无法下单");
            }
            if (product.getStock() == null || product.getStock() < item.getQuantity()) {
                throw new RuntimeException("商品库存不足，无法下单");
            }
            item.setProductPrice(product.getPrice());
            item.setProductName(product.getName());
        }
        // 2. 计算总金额
        BigDecimal totalAmount = items.stream()
                .map(item -> item.getProductPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 生成订单号
        String orderSn = UUID.randomUUID().toString().replace("-", "").substring(0, 20);

        // 4. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setAddressId(addressId);
        order.setOrderSn(orderSn);
        order.setTotalAmount(totalAmount);
        order.setStatus("UNPAID");
        order.setCreateTime(LocalDateTime.now());
        order.setRemark(remark);
        orderMapper.insert(order);

        // 5. 插入订单项
        for (OrderItem item : items) {
            item.setOrderId(order.getOrderId());
            orderItemMapper.insert(item);
        }

        // 6. 创建支付记录
        Payment payment = new Payment();
        payment.setOrderId(order.getOrderId());
        payment.setAmount(totalAmount);
        payment.setStatus("PENDING");
        payment.setCreateTime(LocalDateTime.now());
        paymentMapper.insert(payment);

        return order;
    }

    @Override
    public List<Order> getOrdersByUserId(Integer userId) {
        return orderMapper.selectByUserId(userId);
    }

    @Override
    public Order getOrderDetail(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
            // 可将items设置到order的VO对象中，或返回自定义OrderDetailVO
        }
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Integer userId, Integer orderId, String payMethod) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId) || !"UNPAID".equals(order.getStatus())) {
            return false;
        }
        // 1. 更新订单状态和支付时间
        orderMapper.updateOrderStatus(orderId, "PAID");
        orderMapper.updatePayTime(orderId, LocalDateTime.now());
        // 2. 更新支付记录
        Payment payment = paymentMapper.selectByOrderId(orderId);
        if (payment != null) {
            paymentMapper.updatePaymentStatus(payment.getPaymentId(), "SUCCESS");
            paymentMapper.updatePayMethod(payment.getPaymentId(), payMethod);
        }
        // 3. 扣减库存、增加销量
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        for (OrderItem item : items) {
            Product product = productService.getProductById(item.getProductId());
            if (product != null) {
                int newStock = product.getStock() - item.getQuantity();
                if (newStock < 0) {
                    throw new RuntimeException("商品库存不足，支付失败");
                }
                product.setStock(newStock);
                if (product.getSales() == null) product.setSales(0);
                product.setSales(product.getSales() + item.getQuantity());
                productService.updateProduct(product, product.getSellerId(), "admin");
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Integer userId, Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId) || !"UNPAID".equals(order.getStatus())) {
            return false;
        }
        orderMapper.updateOrderStatus(orderId, "CANCELLED");
        Payment payment = paymentMapper.selectByOrderId(orderId);
        if (payment != null) {
            paymentMapper.updatePaymentStatus(payment.getPaymentId(), "FAILED");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmOrder(Integer userId, Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId) || !"SHIPPED".equals(order.getStatus())) {
            return false;
        }
        orderMapper.updateOrderStatus(orderId, "COMPLETED");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refundOrder(Integer userId, Integer orderId, String reason) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId) || !"PAID".equals(order.getStatus())) {
            return false;
        }
        orderMapper.updateOrderStatus(orderId, "REFUNDING");
        // 这里可以添加退款记录到数据库，暂时简化处理
        return true;
    }

    @Override
    public Payment getPaymentByOrderId(Integer orderId) {
        return paymentMapper.selectByOrderId(orderId);
    }

    @Override
    public OrderDetailVO getOrderDetailVO(Integer orderId, Integer userId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) return null;
        // 买家查自己的订单
        if (userId != null) {
            // 先判断是否买家本人
            if (order.getUserId().equals(userId)) {
                // 允许
            } else {
                // 判断是否为卖家，卖家能看到自己卖出的商品订单
                List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
                boolean isSellerOrder = items.stream().anyMatch(item -> {
                    // 需要查商品的sellerId
                    Product product = productMapper.selectById(item.getProductId());
                    return product != null && product.getSellerId().equals(userId);
                });
                if (!isSellerOrder) return null;
            }
        }
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        UserAddress addr = userAddressMapper.selectById(order.getAddressId());
        OrderDetailVO vo = new OrderDetailVO();
        vo.setOrder(order);
        vo.setItems(items);
        if (addr != null) {
            vo.setReceiverName(addr.getReceiverName());
            vo.setReceiverPhone(addr.getPhone());
            vo.setShippingAddress(addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getDetailAddress());
        }
        return vo;
    }

    @Override
    @Transactional
    public boolean deleteOrder(Integer userId, Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId)) return false;
        if (!("CANCELLED".equals(order.getStatus()) || "COMPLETED".equals(order.getStatus()))) return false;
        orderItemMapper.deleteByOrderId(orderId);
        paymentMapper.deleteByOrderId(orderId);
        return orderMapper.deleteOrderByIdAndUser(orderId, userId) > 0;
    }

    @Override
    public List<Order> getOrdersBySellerId(Integer sellerId) {
        return orderMapper.selectBySellerId(sellerId);
    }
    
    @Override
    public int getOrderCountBySellerId(Integer sellerId) {
        return orderMapper.selectCountBySellerId(sellerId);
    }
    
    @Override
    public BigDecimal getTotalRevenueBySellerId(Integer sellerId) {
        return orderMapper.selectTotalRevenueBySellerId(sellerId);
    }
    
    @Override
    public int getPendingOrderCountBySellerId(Integer sellerId) {
        return orderMapper.selectPendingOrderCountBySellerId(sellerId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean shipOrder(Integer sellerId, Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) return false;
        
        // 检查订单是否属于该卖家
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        boolean isSellerOrder = items.stream()
                .anyMatch(item -> {
                    // 这里需要根据商品ID查询卖家ID，暂时简化处理
                    return true; // 实际应该查询商品表验证卖家ID
                });
        
        if (!isSellerOrder || !"PAID".equals(order.getStatus())) {
            return false;
        }
        
        orderMapper.updateOrderStatus(orderId, "SHIPPED");
        return true;
    }

    // 管理员端订单管理相关方法实现
    @Override
    public IPage<Order> adminListOrders(int page, int pageSize, String orderSn, String status, Integer userId, String startDate, String endDate) {
        Page<Order> orderPage = new Page<>(page, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        
        // 订单号搜索
        if (orderSn != null && !orderSn.trim().isEmpty()) {
            wrapper.like("order_sn", orderSn.trim());
        }
        
        // 状态筛选
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq("status", status);
        }
        
        // 用户ID筛选
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        
        // 时间范围筛选
        if (startDate != null && !startDate.trim().isEmpty()) {
            wrapper.ge("create_time", startDate + " 00:00:00");
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            wrapper.le("create_time", endDate + " 23:59:59");
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc("create_time");
        
        return orderMapper.selectPage(orderPage, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrderByAdmin(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !"UNPAID".equals(order.getStatus())) {
            return false;
        }
        orderMapper.updateOrderStatus(orderId, "CANCELLED");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refundOrderByAdmin(Integer orderId, String reason, String remark, Double amount) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !("PAID".equals(order.getStatus()) || "SHIPPED".equals(order.getStatus()))) {
            return false;
        }
        
        // 更新订单状态为退款中
        orderMapper.updateOrderStatus(orderId, "REFUNDING");
        
        // 这里可以添加退款记录到数据库，暂时简化处理
        // 实际项目中应该创建退款记录表，记录退款金额、原因、备注等信息
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrderByAdmin(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) return false;
        
        // 只有已取消、已完成或已退款的订单才能删除
        if (!("CANCELLED".equals(order.getStatus()) || "COMPLETED".equals(order.getStatus()) || "REFUNDED".equals(order.getStatus()))) {
            return false;
        }
        
        orderItemMapper.deleteByOrderId(orderId);
        paymentMapper.deleteByOrderId(orderId);
        return orderMapper.deleteById(orderId) > 0;
    }

    @Override
    public Map<String, Object> getAdminOrderStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总订单数
        stats.put("totalOrders", orderMapper.selectCount(null));
        
        // 总营收（已完成的订单）
        BigDecimal totalRevenue = orderMapper.selectTotalRevenue();
        stats.put("totalRevenue", totalRevenue != null ? totalRevenue.doubleValue() : 0.0);
        
        // 待处理退款数
        stats.put("pendingRefunds", orderMapper.selectCount(new QueryWrapper<Order>().eq("status", "REFUNDING")));
        
        // 今日订单数
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime tomorrow = today.plusDays(1);
        stats.put("todayOrders", orderMapper.selectCount(
            new QueryWrapper<Order>()
                .ge("create_time", today)
                .lt("create_time", tomorrow)
        ));
        
        return stats;
    }
} 